﻿using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
using System;
using System.Xml;
using System.Linq;

namespace Yonyou.U8.QuickImport
{
    internal class XmlAdmin
    {
        public static string ClearEmptyNode(string xml)
        {
            string text = Path.Combine(Context.QIPath, "data_temp.xml");
            try
            {
                SaveToLocal(xml, text);
                XDocument xDocument = XDocument.Load(text);
                XElement root = xDocument.Root;
                IEnumerable<XElement> enumerable = root.Elements();
                if (enumerable == null)
                {
                    return xml;
                }
                int num = enumerable.Count();
                IList<XElement> list = new List<XElement>();
                for (int i = 0; i < num; i++)
                {
                    XElement xElement = enumerable.ElementAt(i);
                    ClearByScan(xElement, list);
                }
                foreach (XElement item in list)
                {
                    item.Remove();
                }
                GC.Collect();
                return xDocument.ToString();
            }
            catch
            {
                return xml;
            }
            finally
            {
                try
                {
                    if (File.Exists(text))
                    {
                        File.Delete(text);
                    }
                }
                catch
                {
                }
            }
        }

        private static void SaveToLocal(string xml, string path)
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(xml);
            xmlDocument.Save(path);
            GC.Collect();
        }

        private static void ClearByScan(XElement xElement, IList<XElement> waitForDels)
        {
            if (!xElement.HasElements && !xElement.HasAttributes && string.IsNullOrEmpty(xElement.Value))
            {
                waitForDels.Add(xElement);
                return;
            }
            IEnumerable<XElement> enumerable = xElement.Elements();
            if (enumerable != null)
            {
                int num = enumerable.Count();
                for (int i = 0; i < num; i++)
                {
                    XElement xElement2 = enumerable.ElementAt(i);
                    ClearByScan(xElement2, waitForDels);
                }
            }
        }
    }
}